import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm, Space, Upload } from 'antd';
import ProCard from '@ant-design/pro-card';
import { BetaSchemaForm, ProFormInstance } from '@ant-design/pro-form';

import styles from './index.less';
import { useRequest } from '@/hooks';
import { ProColumns } from '@ant-design/pro-table/lib/typing';
import { ProFormColumnsType } from '@ant-design/pro-form/lib/components/SchemaForm';
import { ProCoreActionType } from '@ant-design/pro-utils/lib/typing';
import { SubjectContext } from '@/layout';

export default () => {

    const tabActiveKeyState = React.useState<string>('base');
    const [selectedRow, selectedRowChange] = React.useState<any>();

    const {subject} = React.useContext(SubjectContext)


    const formRef = React.useRef<ProFormInstance>();
    const columns: ProColumns[] & ProFormColumnsType[] = [
        {
            dataIndex: 'id',
            hideInTable: true,
            hideInSearch: true,
            formItemProps: {
                hidden: true,
            }
        },
        {
            hideInSearch: true,
            hideInForm: true,
            sorter: true,
            title: '序号',
            render: (_: any, __: any, index: any) => index + 1
        },
        {
            key: 'name',
            title: '患者姓名',
            sorter: true,
            dataIndex: 'name',
            formItemProps: {
                rules: [{required: true}]
            }
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            formItemProps: {
                rules: [{required: true}]
            }
        },
        {
            title: '年龄',
            dataIndex: 'age',
            sorter: true,
            valueType: 'digit',
            formItemProps: {
                rules: [{required: true}]
            }
        },
        {
            title: '报告信息',
            dataIndex: 'report',
            hideInSearch: true,
            hideInForm: true,
            render: (_: any, entity: { report: string | undefined; }) => {
                return entity.report ? <a target='_blank' href={entity.report}>点击查看报告</a>
                    : <a style={{color: 'black'}}>暂无报告</a>
            }
        },
        {
            title: '采样日期',
            dataIndex: 'samplingDate',
            sorter: true,
            hideInSearch: true,
            valueType: 'dateTime',
            formItemProps: {
                rules: [{required: true}],
                format: 'yyyy-MM-dd HH:mm:ss'
            },
        },
        {
            title: '促排方式',
            dataIndex: 'excretion',
            valueEnum: {
                '人工周期': '人工周期',
                '自然周期': '自然周期'
            },
            formItemProps: {
                rules: [{required: true}],
            }
        },
        {
            title: '送检医院',
            dataIndex: 'hospital',
            hideInSearch: true,
            formItemProps: {
                rules: [{required: true}],
            }
        },
        {
            title: '主治医生',
            dataIndex: 'doctor',
            readonly: true,
            hideInForm: true,
            hideInSearch: true,
        },
        {
            title: '子宫内膜活检组织',
            dataIndex: 'biopsy',
            valueEnum: {
                'P+3': 'P+3',
                'P+5': 'P+5',
                'P+7': 'P+7',
                'LH+5': 'LH+5',
                'LH+7': 'LH+7',
                'LH+9': 'LH+9',
            },
            formItemProps: {
                rules: [{required: true}],
            }
        },
        {
            title: 'LH峰值/行黄体酮',
            dataIndex: 'lhDate',
            valueType: 'dateTime',
            sorter: true,
            hideInSearch: true,
            formItemProps: {
                rules: [{required: true}],
                format: 'yyyy-MM-dd HH:mm:ss'
            },
        },
        {
            title: '种植失败次数',
            dataIndex: 'failCount',
            name: 'failCount',
            valueType: 'digit',
            sorter: true,
            formItemProps: {
                rules: [{required: true}],
            }
        },
        {
            title: '销售名字',
            dataIndex: 'sale',
            hideInSearch: true,
            formItemProps: {
                rules: [{required: true}],
            }
        },
        {
            title: '支付时间',
            dataIndex: 'fillDate',
            hideInSearch: true,
            readonly: true,
            hideInForm: true,
            valueType: 'dateTime',
            formItemProps: {
                name: '_',
                disabled: true
            }
        },
        {
            title: '操作',
            fixed: 'right',
            width: 180,
            hideInForm: true,
            hideInSearch: true,
            render: (_: React.ReactNode, entity: any, __: number, action: ProCoreActionType | undefined) => {
                return <Space>
                    <a style={{color: 'darkseagreen'}} onClick={() => {
                        selectedRowChange(entity)
                        tabActiveKeyState[1]('edit')
                    }}>编辑信息</a>
                    <Upload multiple={false}
                            showUploadList={false}
                            beforeUpload={async (file) => {
                                const form = new FormData()
                                form.append('report', file)
                                message.loading({
                                    key: 0x11,
                                    content: '报告上传中...'
                                })
                                const {data} = await useRequest({
                                    url: `/patient/report/${entity.id}`,
                                    method: 'POST',
                                    data: form
                                })
                                message.success({
                                    key: 0x11,
                                    content: '上传成功',
                                    duration: 0.8
                                })
                                action?.reload()
                                return false
                            }}>
                        <a>上传报告</a>
                    </Upload>
                    <Popconfirm
                        title='是否确认删除？'
                        onConfirm={async () => {
                            await useRequest({
                                url: `/patient/${entity.id}`,
                                method: 'DELETE',
                            })
                            message.success({
                                content: '删除成功',
                                duration: 0.5,
                                key: 0x11
                            })
                            action?.reload()
                        }}>
                        <a type='link' style={{color: 'red'}}>删除</a>
                    </Popconfirm>
                </Space>
            }
        }
    ];

    return <PageContainer
        title='患者信息管理'
        subTitle='查看、修改患者信息以及上传报告'
        className={styles.pageContainer}
        tabList={[{tab: '基本信息', key: 'base'}, {tab: '信息编辑', key: 'edit'}]}
        tabActiveKey={tabActiveKeyState[0]}
        extra={[
            <Button key='edit' type='primary' onClick={() => {
                selectedRowChange(null)
                tabActiveKeyState[1]('edit');
            }}>
                添加
            </Button>
        ]}
        footer={tabActiveKeyState[0] === 'edit' ?
            [
                <Button key='edit'
                        type='primary'
                        onClick={async () => {
                            const fieldsValue = await formRef.current?.validateFieldsReturnFormatValue?.()
                            message.loading({
                                key: 0x11,
                                content: '上传中....'
                            })
                            await useRequest({
                                url: '/patient',
                                method: 'POST',
                                data: fieldsValue
                            })
                            message.success({
                                content: '修改成功',
                                key: 0x11,
                                duration: 0.8
                            })
                        }}>
                    确认
                </Button>,
            ] : []}
        onTabChange={async (e) => {
            tabActiveKeyState[1](e);
        }}>
        {
            tabActiveKeyState[0] === 'base' &&
            <ProTable
                columns={columns}
                scroll={{x: 1700}}
                request={async (params) => {
                    if (subject?.role !== 1) {
                        subject?.role === 3 && (params.doctor = subject?.name)
                        params.hospital = subject?.hospital
                    }
                    Object.entries(params).forEach(([key, value]) => {
                        value === '' && delete params[key]
                    })
                    const {data} = await useRequest({
                        url: '/patient',
                        params: params
                    })
                    return {
                        data: data.records,
                        total: data.total
                    }
                }}
                bordered
                rowKey='id'
            />
        }
        {
            tabActiveKeyState[0] === 'edit' &&
            <Space direction='vertical' className={styles.editTab}>
                <ProCard title='信息编辑' className={styles.card}>
                    <BetaSchemaForm
                        formRef={formRef}
                        className={styles.form}
                        layout='horizontal'
                        labelCol={{span: 5}}
                        submitter={false}
                        initialValues={selectedRow}
                        columns={columns}
                    />
                </ProCard>
            </Space>
        }
    </PageContainer>;
}
